import errorCode from "@/constants/errorCode";
import config from 'config/env';
import {
	getToken
} from '@/utils/auth'
import store from '@/store'
const myRequest = (options) => { //暴露一个function：myRequest，使用options接收页面传过来的参数
	return new Promise((resolve, reject) => { //异步封装接口，使用Promise处理异步请求
		if (options.showLoading) {
			uni.showLoading({
				title: '加载中'
			});
		}
		let url = options.url;
		
		//#ifndef H5 
		url = config.basePath + options.url
		//#endif
		uni.request({ //发送请求
			url: url, //接收请求的API
			method: options.method || 'GET', //接收请求的方式,如果不传默认为GET
			header: {
				'hx-token': getToken(), // 请求token
				'timestamp': new Date().getTime(),
				//#ifdef MP-WEIXIN
				'client-type': 'WX-MA', //客户端微信小程序
				'app-id': uni.getAccountInfoSync().miniProgram.appId, //小程序appId
				//#endif
				//#ifdef APP-PLUS
				'client-type': 'APP', //客户端类型APP
				'tenant-id': config.tenantId,
				//#endif
				//#ifdef H5
				'client-type': 'H5', //客户端H5
				'tenant-id': config.tenantId,
				//#endif
				//#ifdef MP-ALIPAY
				'client-type': 'ALI-MA', //客户端支付宝小程序
				'app-id': config.aliAppId, //小程序appId
				//#endif
			},
			data: options.data || {}, //接收请求的data,不传默认为空
			//接口请求成功
			success: (res) => {
				if (res.statusCode != 200) {
					uni.$emit('z-paging-error-emit');
					return uni.showModal({
						title: '提示',
						content: errorCode[res.statusCode] || res.data.msg || "未知错误",
						success(res) {}
					});
					reject();
				}
				if (res.data.code != 0) {
					if (res.data.code === 40001) { // token 过期

						if (!getApp().globalData.isLoading) {
							getApp().globalData.isLoading = true;
							// #ifdef MP-WEIXIN
							store.dispatch("LoginWxMa").then((res) => {
								var pages = getCurrentPages(); // 获取页面栈
								var currPage = pages[pages.length - 1]; // 当前页面
								currPage.onLoad(currPage.options)
								getApp().globalData.isLoading = false;
							})
							// #endif
							// #ifdef MP-ALIPAY
							store.dispatch("LoginAliMa").then((res) => {
								var pages = getCurrentPages(); // 获取页面栈
								var currPage = pages[pages.length - 1]; // 当前页面
								currPage.onLoad(currPage.options)
								getApp().globalData.isLoading = false;
							})
							// #endif
							// #ifndef MP-WEIXIN || MP-ALIPAY
							var pages = getCurrentPages(); // 获取页面栈
							var currPage = pages[pages.length - 1]; // 当前页面
							if (currPage) {
								let curParam = currPage.options
								// 拼接参数
								let redirectUrl = '/' + currPage.route
								if (curParam != null) {
									// 拼接参数
									let param = ''
									for (let key in curParam) {
										param += '&' + key + '=' + curParam[key]
									}
									param = param.substr(1)
									redirectUrl = redirectUrl + '?' + param
									redirectUrl = encodeURIComponent(redirectUrl)
								}
								uni.reLaunch({
									url: '/pages/login/index?redirectUrl=' +
										redirectUrl
								});
								//延迟1秒关闭
								setTimeout(function() {
									getApp().globalData.isLoading = false;
								}, 1000);
							}
							reject("请登录");
							// #endif
						}
						reject("hx-token过期")
					} else if (res.data.code === 40002) {
						if (!getApp().globalData.isLoading) {
							getApp().globalData.isLoading = true;
							var pages = getCurrentPages(); // 获取页面栈
							var currPage = pages[pages.length - 1]; // 当前页面
							if (currPage) {
								let curParam = currPage.options
								// 拼接参数
								let redirectUrl = '/' + currPage.route
								if (curParam != null) {
									// 拼接参数
									let param = ''
									for (let key in curParam) {
										param += '&' + key + '=' + curParam[key]
									}
									param = param.substr(1)
									redirectUrl = redirectUrl + '?' + param
									redirectUrl = encodeURIComponent(
										redirectUrl)
								}
								uni.reLaunch({
									url: '/pages/login/index?redirectUrl=' +
										redirectUrl
								});
								//延迟1秒关闭
								setTimeout(function() {
									getApp().globalData.isLoading = false;
								}, 1000);
							}
						}
						reject("请登录");
					} else {
						return uni.showModal({
							title: '提示',
							content: res.data.msg || "未知错误",
							success(res) {}
						});
						reject();
					}
				}
				resolve(res.data) //成功,将数据返回
			},
			fail: (err) => { //失败操作
				uni.$emit('z-paging-error-emit');
				uni.showModal({
					title: '提示',
					content: '接口请求出错：' + err.errMsg,
					success(res) {}
				});
				reject(err)
			},
			complete(res) {
				if (options.showLoading) {
					uni.hideLoading();
				}
			}
		})
	})
}

module.exports = {
	myRequest
}
